package com.hama.iotrust.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;

import com.hama.iotrust.common.util.ExcelUtil;

/**
 * Excel 导出工具
 * 
 * @author Jinjq
 * @since 2013-05-24 20:09:40
 */
public class ExcelUtil {

    /**
     * 根据模板导出Excel， 导出的Excel版本由模板的版本决定
     * 
     * @param templateClassPath 模板的classPath
     * @param beanParams excel模板中用到的变量map
     * @param response
     * @param fileNameWithoutExt 不含扩展名的文件名
     * @throws ParsePropertyException
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static void export(String templateClassPath, Map<String, Object> beanParams, HttpServletResponse response,
                              String fileNameWithoutExt) throws ParsePropertyException, IOException,
                                                        InvalidFormatException {
        InputStream is = ExcelUtil.class.getResourceAsStream(templateClassPath);
        XLSTransformer transformer = new XLSTransformer();
        org.apache.poi.ss.usermodel.Workbook workbook = transformer.transformXLS(is, beanParams);
        String ext;
        if (workbook instanceof XSSFWorkbook) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            ext = ".xlsx";
        } else {
            response.setContentType("application/vnd.ms-excel");
            ext = ".xls";
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodingFileName(fileNameWithoutExt)
                                                  + ext + "\"");
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        is.close();
        os.flush();
        os.close();
    }

    private static String encodingFileName(String fileName) {
        String returnFileName = fileName;
        try {
            String encoding = "GBK";
            returnFileName = URLEncoder.encode(fileName, "UTF-8");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes(encoding), "ISO8859-1");
                returnFileName = StringUtils.replace(returnFileName, " ", "%20");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnFileName;
    }
}
